<template>
  <el-select v-model="val" :disabled="disabled" clearable filterable placeholder="请选择" size="mini" @change="onChange">
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
  </el-select>
</template>

<script>
import { isArray } from '@neu/biz-core/utils/utils'
import store from './store'
export default {
  name: 'DatasourceSelect',
  props: {
    url: {
      type: [Array, String],
      default: ''
    },
    value: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    valueKey: {
      type: String,
      default: 'value'
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    responseKey: {
      type: String,
      default: 'data'
    }
  },
  data() {
    return {
      val: this.value,
      options: []
    }
  },
  watch: {
    url(newVal, oldVal) {
      this.fetch(newVal)
    },
    responseKey(newVal, oldVal) {
      this.fetch(this.url)
    },
    valueKey(newVal, oldVal) {
      this.fetch(this.url)
    },
    labelKey(newVal, oldVal) {
      this.fetch(this.url)
    }
  },
  created() {
    if (this.url !== '') {
      this.fetch(this.url)
    }
  },
  methods: {
    onChange() {
      this.$emit('input', this.val)
    },
    fetch(url) {
      const that = this
      store.fetch(url)
        .then(function(response) {
          let options = []
          if (that.responseKey) {
            options = response.data[that.responseKey]
          } else {
            options = response.data
          }
          if (!isArray(options)) {
            return
          }
          options = options.map(it => {
            return {
              value: it[that.valueKey],
              label: it[that.labelKey]
            }
          })

          that.options = options
        })
        .catch(function(error) {
          console.error(error)
        })
    }
  }
}
</script>
